package com.samnative.pineapple.main;

import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.samnative.pineapple.adapter.ShoppingCarAdapter;
import com.samnative.pineapple.entity.ProductDetailModel;
import com.samnative.pineapple.entity.ProductSkuModel;
import com.samnative.pineapple.entity.ShoppingCarModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.instance.UserInfo;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.widget.ProductStandardPop;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车页面
 */
public class ShoppingCartActivity extends BaseActivity implements
        View.OnClickListener, ShoppingCarAdapter.OnBuyItem, ProductStandardPop.OnStandrad {

    /**
     * 展示购物商品详情
     */
    private ExpandableListView melv;
    /**
     * 购物车列表适配器
     */
    private ShoppingCarAdapter cpadapter;
    /**
     * 全选
     */
    private ImageView ivAllCheck;
    /**
     * 浮点数格式化
     */
    private DecimalFormat df = new DecimalFormat("0.00");
    /**
     * 结算按钮
     */
    private LinearLayout btnGoaccount;
    /**
     * 显示结算数量
     */
    private TextView count_tv;
    /**
     * 选中商品数量
     */
    private int totalNum;
    /**
     * 总价格显示
     */
    private TextView amount_tv, amount_unit_tv, bull_tv, bull_unit_tv;
    /**
     * 当前要删除的商品下标
     */
    private int deleteGroupPosition, deleteChildPostion;
    /**
     * 当前要编辑规格的商品
     */
    private int editSpecGroupPosition, editSpecChildPostion;
    /**
     * 默认图
     */
    private RelativeLayout rlDefaultLayout;
    /**
     * 标题
     */
    private TextView tv_title;
    /**
     * 上下文
     */
    private Context context;
    /**
     * 商品规格选择
     */
    private ProductStandardPop gspw;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shopping_cart;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        context = this;
        findViewById(R.id.tv_back).setOnClickListener(this);
        // findViewById(R.id.btn_default_layout).setOnClickListener(this);
        tv_title = (TextView) findViewById(R.id.tv_title);
        amount_tv = (TextView) findViewById(R.id.amount_tv);
        amount_unit_tv = (TextView) findViewById(R.id.amount_unit_tv);
        bull_tv = (TextView) findViewById(R.id.bull_tv);
        bull_unit_tv = (TextView) findViewById(R.id.bull_unit_tv);
        btnGoaccount = (LinearLayout) findViewById(R.id.btn_goaccount);
        btnGoaccount.setOnClickListener(this);
        count_tv = (TextView) findViewById(R.id.count_tv);
        ivAllCheck = (ImageView) findViewById(R.id.iv_ischeckall);
        ivAllCheck.setOnClickListener(this);
        rlDefaultLayout = (RelativeLayout) findViewById(R.id.rl_default_data_layout);
        cpadapter = new ShoppingCarAdapter(context);
        cpadapter.setOnBuyItem(this);
        melv = (ExpandableListView) findViewById(R.id.shopping_car_lv);
        melv.setGroupIndicator(null);
        melv.setAdapter(cpadapter);
        gspw = new ProductStandardPop(context);
        gspw.setOnStanDrad(this);
        gspw.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                cpadapter.setFinish(true);
                cpadapter.notifyDataSetChanged();
            }
        });

        // 展开全部item
        for (int i = 0; i < cpadapter.getGroupCount(); i++) {
            melv.expandGroup(i);
        }
        // 屏蔽item折叠开关
        melv.setOnGroupClickListener(new OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                // TODO Auto-generated method stub
                return true;
            }
        });

    }


    /**
     * 请求数据
     */
    public void requestData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("_apiname", "shopingcart.index.goodslist");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));

        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result.getJSONObject("data");
                    JSONObject jsonCar = jsonData
                            .getJSONObject("cardata");
                    String cargoodsgount = jsonCar
                            .getString("cargoodsgount");
                    if (!cargoodsgount.equals("")
                            && !cargoodsgount.equals("0")) {
                        tv_title.setText("购物车(" + cargoodsgount + ")");
                    } else {
                        tv_title.setText("购物车");
                    }

                    JSONArray jsonArr = jsonData
                            .getJSONArray("goodsList");
                    setDatas(jsonArr.toString());

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

    }

    /**
     * 设置数据
     *
     * @param jsonArr
     */
    public void setDatas(String jsonArr) {
        Gson gson = new Gson();
        List<ShoppingCarModel> datas = gson.fromJson(jsonArr.toString(),
                new TypeToken<List<ShoppingCarModel>>() {
                }.getType());
        UserInfo.getInstance().getListShoppingCar().clear();
        UserInfo.getInstance().getListShoppingCar().addAll(datas);
        if (UserInfo.getInstance().getListShoppingCar().size() == 0) {
            rlDefaultLayout.setVisibility(View.VISIBLE);
        }
        setRsult();
        cpadapter.notifyDataSetChanged();
        for (int i = 0; i < cpadapter.getGroupCount(); i++) {
            melv.expandGroup(i);
        }
    }

    // 点击监听
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            // case R.id.btn_default_layout:
            // Intent intentMain = new Intent(context, MainActivity.class);
            // intentMain.putExtra(ConstsObject.GO_TO_MAINACTIVITY_WHERE,
            // ConstsObject.GO_TO_UYAC_PRODUCT);
            // startActivity(intentMain);
            // break;
            case R.id.btn_goaccount:

                if (UserInfo.getInstance().getListShoppingCar().size() == 0) {
                    ToastUtils.showShort("购物车是空的!");
                    break;
                }

                if (totalNum == 0) {
                    ToastUtils.showShort("请选择结算商品!");
                    break;
                }
                if (AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "").isEmpty()) {
                    // startActivity(new Intent().setClass(context,
                    // QuickLoginActivity.class));
                    break;
                }

//                Intent intent = new Intent(context,
//                        ProductOrderConfirmActivity.class);
//                intent.putExtra("items", getShoppingPostList(UserInfo.getInstance()
//                        .getListShoppingCar()));
//                startActivity(intent);
                break;
            case R.id.iv_ischeckall:

                // 判断是否有选中任何一个店铺
                boolean isCheck = true;
                for (int i = 0; i < UserInfo.getInstance().getListShoppingCar()
                        .size(); i++) {
                    if (!UserInfo.getInstance().getListShoppingCar().get(i)
                            .isChecked()) {
                        isCheck = false;
                        break;
                    }
                }

                // 全选或全不选
                isCheck = !isCheck;
                ivAllCheck
                        .setImageResource(isCheck ? R.mipmap.ic_check_pressed_toolbar
                                : R.mipmap.ic_check_toolbar);
                for (int i = 0; i < UserInfo.getInstance().getListShoppingCar()
                        .size(); i++) {
                    UserInfo.getInstance().getListShoppingCar().get(i)
                            .setChecked(isCheck);
                    List<ShoppingCarModel.GoodsData> items = UserInfo.getInstance()
                            .getListShoppingCar().get(i).getGoodsData();
                    for (int j = 0; j < items.size(); j++) {
                        if (items.get(j).getEnable().equals("1")) {
                            items.get(j).setChecked(isCheck);
                        }

                    }
                }
                setRsult();
                cpadapter.notifyDataSetChanged();
                break;
        }

    }

    /**
     * 请求删除购物车商品
     */
    public void requestDeleteItem(String carId, String businessId) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("cartid", carId);
        map.put("businessid", businessId);
        map.put("_apiname", "shopingcart.index.delgoods");
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                ToastUtils.showShort("删除成功!");

                UserInfo.getInstance().getListShoppingCar()
                        .get(deleteGroupPosition).getGoodsData()
                        .remove(deleteChildPostion);
                if (UserInfo.getInstance().getListShoppingCar()
                        .get(deleteGroupPosition).getGoodsData().size() == 0) {
                    UserInfo.getInstance().getListShoppingCar()
                            .remove(deleteGroupPosition);
                }
                setRsult();
                cpadapter.notifyDataSetChanged();

                if (UserInfo.getInstance().getListShoppingCar().size() == 0) {
                    rlDefaultLayout.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    /**
     * 获取商品的所有规格
     */
    public void requestSpecItem(String productid, final String skuid) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("productid", productid);
        map.put("_apiname", "shopingcart.index.choseGoosSpec");
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject json = result;
                    ProductDetailModel model = GsonUtils.fromJson(json
                                    .getJSONObject("data").toString(),
                            ProductDetailModel.class);
                    gspw.setData(model.getSpec(), model.getSku(), skuid);
                    gspw.setMinNum(1);
                    gspw.setBtn(1, false);
                    gspw.showAtLocation(melv, Gravity.CENTER, 0, 0);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 计算总计价格与购买总数
     */
    public void setRsult() {
        totalNum = 0;
        double totalMoney = 0.00d;
        double totaBull = 0.00d;
        for (int i = 0; i < UserInfo.getInstance().getListShoppingCar().size(); i++) {
            if (!UserInfo.getInstance().getListShoppingCar().get(i).isChecked()) {
                continue;
            }
            List<ShoppingCarModel.GoodsData> items = UserInfo.getInstance()
                    .getListShoppingCar().get(i).getGoodsData();
            for (int j = 0; j < items.size(); j++) {
                if (!items.get(j).isChecked()) {
                    continue;
                }
                totalNum += Integer.parseInt(items.get(j).getProductnum());
                int tempNum = Integer.parseInt(items.get(j).getProductnum());
                // 获取商品单价
                double tempPrice = items.get(j).getProuctprice();
                totalMoney += tempNum * tempPrice;

                // 计算积分
                if (items.get(j).getBullamount() > 0) {
                    double tempBull = items.get(j).getBullamount();
                    totaBull += tempNum * tempBull;
                }
            }
        }
        count_tv.setText("结算(" + totalNum + ")");
        String totaBullstr = totaBull > 0 ? (df.format(totaBull)) : "";
        if (totalMoney == 0) {
            amount_tv.setText("");
            amount_unit_tv.setText("");
            bull_tv.setText("+" + totaBullstr);
            bull_unit_tv.setText("积分");
        } else {
            if (totaBull == 0) {
                amount_tv.setText(df.format(totalMoney));
                amount_unit_tv.setText("¥");
                bull_tv.setText("");
                bull_unit_tv.setText("");
            } else {
                amount_tv.setText(df.format(totalMoney));
                amount_unit_tv.setText("¥");
                bull_tv.setText("+" + totaBullstr);
                bull_unit_tv.setText("积分");
            }
        }
        if (totalMoney == 0 && totaBull == 0) {
            amount_tv.setText("0.00");
            amount_unit_tv.setText("¥");
            bull_tv.setText("");
            bull_unit_tv.setText("");
        }
    }

    // ======================================================监听购物车变化Start

    @Override
    public void checkedGroup(int groupPosition) {
        // TODO Auto-generated method stub
        if (UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                .isChecked()) {
            // 店铺已选中
            UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                    .setChecked(false);
            List<ShoppingCarModel.GoodsData> items = UserInfo.getInstance()
                    .getListShoppingCar().get(groupPosition).getGoodsData();
            for (int i = 0; i < items.size(); i++) {
                items.get(i).setChecked(false);
            }

        } else {
            // 店铺未选中
            UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                    .setChecked(true);
            List<ShoppingCarModel.GoodsData> items = UserInfo.getInstance()
                    .getListShoppingCar().get(groupPosition).getGoodsData();
            for (int i = 0; i < items.size(); i++) {
                if (items.get(i).getEnable().equals("1")) {
                    items.get(i).setChecked(true);
                }
            }
        }
        setRsult();
        isAllCheck();
        cpadapter.notifyDataSetChanged();
    }

    @Override
    public void checkedChild(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        if (UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                .getGoodsData().get(childPosition).isChecked()) {
            // 商品已选中
            UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                    .getGoodsData().get(childPosition).setChecked(false);

            // 判断店家商品是否全部取消
            boolean isAllCancel = false;
            List<ShoppingCarModel.GoodsData> item = UserInfo.getInstance()
                    .getListShoppingCar().get(groupPosition).getGoodsData();
            for (int i = 0; i < item.size(); i++) {
                if (item.get(i).isChecked()) {
                    isAllCancel = true;
                    break;
                }
            }

            UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                    .setChecked(isAllCancel);

        } else {
            // 商品未选中
            UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                    .getGoodsData().get(childPosition).setChecked(true);

            UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                    .setChecked(true);
        }
        setRsult();
        isAllCheck();
        cpadapter.notifyDataSetChanged();
    }

    @Override
    public void deleteProduct(final int groupPosition, final int childPosition) {

        MessageDialog.show(this, null, "是否删除该商品?", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        deleteGroupPosition = groupPosition;
                        deleteChildPostion = childPosition;
                        requestDeleteItem(UserInfo.getInstance()
                                        .getListShoppingCar().get(groupPosition)
                                        .getGoodsData().get(childPosition).getCartid(),
                                UserInfo.getInstance().getListShoppingCar()
                                        .get(groupPosition).getBusinessid());
                        setRsult();
                        cpadapter.notifyDataSetChanged();
                        return false;
                    }
                });

    }

    @Override
    public void upNum() {
        setRsult();
    }

    @Override
    public void editSpec(int groupPosition, int childPosition) {
        editSpecGroupPosition = groupPosition;
        editSpecChildPostion = childPosition;
        requestSpecItem(
                UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                        .getGoodsData().get(childPosition).getProductid(),
                UserInfo.getInstance().getListShoppingCar().get(groupPosition)
                        .getGoodsData().get(childPosition).getSkuid());
    }

    // ======================================================监听购物车变化End

    /**
     * 是否全选了 是刚把全选按钮勾上
     */
    public void isAllCheck() {
        boolean isCheck = true;
        for (int i = 0; i < UserInfo.getInstance().getListShoppingCar().size(); i++) {
            if (UserInfo.getInstance().getListShoppingCar().get(i).isChecked() == false) {
                isCheck = false;
                break;
            }
            ShoppingCarModel model = UserInfo.getInstance()
                    .getListShoppingCar().get(i);
            for (int j = 0; j < model.getGoodsData().size(); j++) {
                if (model.getGoodsData().get(j).isChecked() == false) {
                    isCheck = false;
                    break;
                }
            }
        }
        ivAllCheck
                .setImageResource(isCheck ? R.mipmap.ic_check_pressed_toolbar
                        : R.mipmap.ic_check_toolbar);
    }

    /**
     * 封装购物车提交数据
     *
     * @param datas
     */
    public String getShoppingPostList(List<ShoppingCarModel> datas) {
        StringBuilder cartIds = new StringBuilder();
        for (int i = 0; i < datas.size(); i++) {
            if (!datas.get(i).isChecked()) {
                continue;
            }
            List<ShoppingCarModel.GoodsData> items = datas.get(i)
                    .getGoodsData();
            for (int j = 0; j < items.size(); j++) {
                if (!items.get(j).isChecked()) {
                    continue;
                }
                cartIds.append(items.get(j).getCartid());
                cartIds.append(",");
            }
        }
        if (cartIds.length() > 0 && cartIds.charAt(cartIds.length() - 1) == ',') {
            cartIds.deleteCharAt(cartIds.length() - 1);
        }
        return cartIds.toString();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
        ivAllCheck.setImageResource(R.mipmap.ic_check_toolbar);
    }


    /**
     * 更改商品规格
     */
    public void requestChooseSpec(ProductSkuModel currentSku, int num) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("productid", currentSku.getProductid());
        map.put("productnum", num + "");
        map.put("skuid", currentSku.getId());
        map.put("oldcartid",
                UserInfo.getInstance().getListShoppingCar()
                        .get(editSpecGroupPosition).getGoodsData()
                        .get(editSpecChildPostion).getCartid());
        map.put("_apiname", "shopingcart.index.updateSpecgoods");
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                requestData();
            }
        });
    }

    // =====================================================================

    @Override
    public void buyNow(ProductSkuModel currentSku, int num) {
        // TODO Auto-generated method stub
    }

    @Override
    public void addCar(ProductSkuModel currentSku, int num) {
        // TODO Auto-generated method stub
        gspw.dismiss();
        requestChooseSpec(currentSku, num);
    }

    @Override
    public void getStandrad(ProductSkuModel currentSku, int num, String content) {
        // TODO Auto-generated method stub
    }
}
